package com.leilei.config;

import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;
import com.leilei.entity.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lei
 * @create 2022-04-21 16:27
 * @desc 全局异常拦截
 **/
@RestControllerAdvice
@Log4j2
public class ExceptionAdvice {

    /**
     * 全局异常捕获
     * @param e @SentinelResource中定义了 blockHandler 和 faidback 属性，则此处不会捕获，以为 blockHandler 和 failback的优先级最高
     * @return
     */
    @ExceptionHandler({FlowException.class})
    public Result handleFlowException(FlowException e) {
        FlowRule rule = e.getRule();
        log.warn("接口资源:{}已被限流", rule.getRefResource());
        return Result.fail("限流异常!限流配置为:" + JSON.toJSONString(rule));
    }


}
